# -*- coding: utf8 -*-

import re
import requests

from werobot.parser import parse_user_msg
from werobot.reply import TextReply
from werobot.reply import Article, ArticlesReply
from werobot.messages import TextMessage, EventMessage
from django.utils.encoding import smart_str
from django.conf import settings

import run
import handlers
import help

def create_reply(xml):
    msg = parse_user_msg(xml)        
    if isinstance(msg, TextMessage):
        t = smart_str(msg.content)
        reply = run.do_handler(t)
        
    elif isinstance(msg, EventMessage) and msg.type == 'subscribe':
        reply = help.do_subscribe()

    elif isinstance(msg, EventMessage) and msg.type == 'click':
        if msg.key == 'V-help':
            reply = help.do_help()
        elif msg.key == 'V-vip':
            reply = help.do_vip()
        elif msg.key == 'V-fuwu':
            reply = help.do_fuwu()
        else:
            reply = help.do_other()

    elif isinstance(msg, EventMessage) and msg.type == 'location':
        reply = handlers.do_location(msg.latitude, msg.longitude)

    else:
        reply = help.do_other()

   
    if type(reply) is str:
        r = TextReply(message=msg, content=reply)
    elif type(reply) is list:
        r = ArticlesReply(message=msg)
        for article in reply:
            article = Article(*article)
            r.add_article(article)
    reply_xml = r.render()

    return reply_xml

def create_menu(appid, secret, menu_data):
    from werobot.client import Client
    c = Client(appid, secret)
    c.create_menu(menu_data)

